<?php
namespace App\Admin\Ajax\SalesReport;

use App\Models\SalesReport\PaymentDetailJP;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\StreamedResponse;

class PaymentDetailForJPAjax {

    public function paymentDetailForJPExport(){
        return view('sales-report.payment-detail.export-for-jp-modal');
    }

    public function doPaymentDetailForJPExport($param){
        $start = $param['start_date'];
        $end = $param['end_date'];
        $type = $param['type'];
        if(is_null($start) && is_null($end)){
            $time = strtotime("midnight first day of -1 month");
            $startDate = $endDate = date('Y-m-01',$time);
        }elseif(!is_null($start) && is_null($end)){
            $startDate = $endDate = $start;
        }elseif(is_null($start) && !is_null($end)){
            $startDate = $endDate = $end;
        }else{
            $startDate = $start;
            $endDate = $end;
        }
        if(!$type)$type = 1;
        $query = PaymentDetailJP::query()
            ->where('report_date' ,'>=',$startDate)
            ->where('report_date' ,'<=',$endDate)
            ->where('type' ,$type)
            ->with(['account','sku']);
        $head = PaymentDetailJP::getDownloadHeaders();
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="JP月利润明细报表.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(800, function ($re) use ($fp){
                $data = PaymentDetailJP::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }
}
